<template>
    <view style="background-color: #F6F6F6;min-height: 100vh;">
        <u-notice-bar :text="notice"></u-notice-bar>
        <view v-if="uploadImg"  class=" p_20 dis_f_co_c_c">
            <image :src="uploadImg"  mode="widthFix"  style="width: 600rpx"></image>
            <view class="audio-view">
                <view class="play-button-area">
                    <image class="icon-play" :src="playImage" @click="play"></image>
                </view>
                <view class="play-silder">
                    <view class="audio-time">
                        <text>{{currentTimeStr}}</text>
                    </view>
                    <view class="audio-siler">
                        <slider :value="position" :min="0" :max="duration" @changing="onchanging" @change="onchange"></slider>
                    </view>
                    <view class="audio-time">
                        <text>{{timeStr}}</text>
                    </view>
                </view>
            </view>
        </view>
        <view v-else class="dis_f_co_c_c" @click="handleUpload">
            <image src="/static/img/bg.png" class="m_t_50" style="width: 600rpx;height: 600rpx;"></image>
            <view class="f_s_20 f_w_b c_green m_t_10" >点击选择简谱</view>
        </view>

    </view>
</template>

<script>
import {getByKeyApi, getMusicApi, getMyInfoApi} from "@/sheep/api";
import {
    baseUrl
} from "@/sheep/request/baseUrl";
export default {
    data() {
        return {
            notice:'',
            myInfoVo:{},
            uploadImg:'',
            title: "innerAudioContext",
            isPlaying: false,
            isPlayEnd: false,
            currentTime: 0,
            currentTimeStr: '00:00',
            duration: 100,
            timeStr: '00:00:00',
            audioUrl:''
        }
    },
    computed: {
        position() {
            return this.isPlayEnd ? 0 : this.currentTime;
        },
        playImage() {
            return this.isPlaying ? "/static/img/pause.png" : "/static/img/play.png"
        }
    },
    onLoad: function () {

    },
    onUnload() {
        if (this._audioContext != null && this.isPlaying) {
            this.stop();
        }
    },
    onShow() {
        this.getNoticeList()
        this.getMyInfo()
    },
    methods: {
        getMyInfo() {
            getMyInfoApi().then((res) => {
                this.myInfoVo = res.data;
            });
        },
        async getNoticeList() {
            let res = await getByKeyApi("notice");
            res.data.forEach((element) => {
                this.notice += element.configValue + "                     ";
            });
        },
        handleUpload(){
            if (this.myInfoVo.ifhy == false){
                uni.showModal({
                    title: '提示',
                    content: '您当前还未开通会员，是否开通？',
                    success: (res) => {
                        if (res.confirm) {
                            uni.navigateTo({
                                url: '/pages/mine/vipList'
                            })
                        } else if (res.cancel) {
                            console.log('用户点击取消');
                        }
                    }
                });
            }else{
                let that =this
                let token = uni.getStorageSync('token')
                let headerToken = "Bearer " + token
                uni.chooseImage({
                    count: 1,
                    sizeType: ['original', 'compressed'],
                    success: async (res) => {
                        console.log("res", res);
                        let imageSrc = res.tempFilePaths[0] //将图片的地址赋值给imageSrc
                        that.uploadImg = res.tempFilePaths[0] //将图片的地址赋值给imageSrc
                        that.$forceUpdate()
                        that.getMusic()
                    }
                });
            }
        },
        getMusic(){
            getMusicApi().then(res=>{
                this.audioUrl = res.data.urlLink
                this._isChanging = false;
                this._audioContext = null;
                this.createAudio();
                this.isPlaying = false;
                this.play()
            })
        },
        createAudio() {
            var innerAudioContext = this._audioContext = uni.createInnerAudioContext();
            innerAudioContext.autoplay = false;
            innerAudioContext.src = this.audioUrl;
            innerAudioContext.onPlay(() => {
                console.log('开始播放');
            });
            innerAudioContext.onCanplay(() => {
                let timeid = setInterval(() => {
                    if (innerAudioContext.duration) {
                        clearInterval(timeid)
                        this.duration = innerAudioContext.duration || 0;
                        console.log(this.duration)
                        this.timeStr = this.formatSecond(this.duration);
                    }
                }, 500)
            });
            innerAudioContext.onTimeUpdate((e) => {
                if (this._isChanging === true) {
                    return;
                }
                this.currentTime = innerAudioContext.currentTime || 0;
                this.duration = innerAudioContext.duration || 0;
                this.currentTimeStr = this.formatTime(this.currentTime);
                //进度条最大值
                // this.timeStr = this.formatSecond(this.duration);
            });
            innerAudioContext.onEnded(() => {
                this.currentTime = 0;
                this.currentTimeStr = this.formatTime(this.currentTime);
                this.isPlaying = false;
                this.isPlayEnd = true;
            });
            innerAudioContext.onError((res) => {
                this.isPlaying = false;
                console.log(res.errMsg);
                console.log(res.errCode);
            });
            return innerAudioContext;
        },
        onchanging() {
            this._isChanging = true;
        },
        onchange(e) {
            console.log(e.detail.value);
            console.log(typeof e.detail.value);
            this._audioContext.seek(e.detail.value);
            this._isChanging = false;
            const currTimeStr = this.formatTime(e.detail.value)
            this.currentTimeStr = currTimeStr
        },
        play() {
            if (this.isPlaying) {
                this.pause();
                return;
            }
            this.isPlaying = true;
            this._audioContext.play();
            this.isPlayEnd = false;
        },
        pause() {
            this._audioContext.pause();
            this.isPlaying = false;
        },
        stop() {
            this._audioContext.stop();
            this.isPlaying = false;
        },
        formatTime(num) {
            //格式化时间格式
            num = num.toFixed(0);
            let second = num % 60;
            if (second < 10) second = '0' + second;
            let min = Math.floor(num / 60);
            if (min < 10) min = '0' + min;
            return min + ":" + second;
        },
        /**
         * 格式化时间
         * @param {String} date 原始时间格式
         * 格式后的时间：hh:mm:ss
         **/
        formatSecond(seconds) {
            var h = Math.floor(seconds / 3600) < 10 ? '0' + Math.floor(seconds / 3600) : Math.floor(seconds / 3600);
            var m = Math.floor((seconds / 60 % 60)) < 10 ? '0' + Math.floor((seconds / 60 % 60)) : Math.floor((
                seconds / 60 % 60));
            var s = Math.floor((seconds % 60)) < 10 ? '0' + Math.floor((seconds % 60)) : Math.floor((seconds % 60));
            return h + ":" + m + ":" + s;
        }
    }

}
</script>
<style scoped>

</style>
<style>
.audio-view {
    display: flex;
    justify-content: space-between;
    border: 1rpx #dadada solid;
    padding: 20rpx 10rpx;
    background-color: #FFFFFF;
    margin-top: 20px;
    margin-bottom: 20px;
    width: 100%;
    border-radius: 10rpx;
}

.play-time-area {
    display: flex;
    flex-direction: row;
}

.audio-time {
    width: 150rpx;
    line-height: 100rpx;
}

.duration {
    margin-left: auto;
}

.audio-siler {
    width: 100%;
}

.play-silder {
    width: 100%;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.play-button-area {
    display: flex;
    flex-direction: row;
    justify-content: center;
    align-items: center;
    width: 100rpx;
}

.icon-play {
    width: 50rpx;
    height: 50rpx;
    /* margin-top: 5rpx; */
}
</style>
